﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dycox.Reporting.Aggregation
{
    internal abstract class ComparingAggregationContext : AggregationContext
    {
        public ComparingAggregationContext(string dataMember)
            : base(dataMember)
        {

        }

        IComparable _value;

        protected override void Initialize()
        {
            base.Initialize();

            _value = null;
        }

        protected override void Aggregate(object value, object dataObject, System.ComponentModel.PropertyDescriptor property)
        {
            if (value != null)
            {
                IComparable c = value as IComparable;

                if (c == null)
                    throw new InvalidOperationException();

                if (_value == null) _value = c;
                else if (Compare(c, _value)) _value = c;
            }
        }

        protected abstract bool Compare(IComparable current, IComparable @base);

        protected override object FinishAggregate()
        {
            return _value;
        }
    }

    internal class Max : ComparingAggregationContext
    {
        public Max(string dataMember)
            : base(dataMember)
        {

        }

        protected override bool Compare(IComparable current, IComparable @base)
        {
            int diff = current.CompareTo(@base);

            return diff > 0;
        }
    }

    internal class Min : ComparingAggregationContext
    {
        public Min(string dataMember)
            : base(dataMember)
        {

        }

        protected override bool Compare(IComparable current, IComparable @base)
        {
            int diff = current.CompareTo(@base);

            return diff < 0;
        }
    }

}
